package com.ld.oauth2.config.oauth.authorize;

import com.google.common.collect.Lists;
import com.ld.oauth2.model.po.SysPermission;
import com.ld.oauth2.model.po.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class MenuAuthenticationSuccessListener implements AuthenticationSuccessListener {


    @Override
    public void successListener(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal != null && principal instanceof SysUser) {
            SysUser sysUser = (SysUser) principal;
            loadMenuTree(sysUser);
            log.info("successListener  "+sysUser.toString());
        }

    }

    private void loadMenuTree(SysUser sysUser) {
        List<SysPermission> permissionList =
                sysUser.getPermissionList();
        if (CollectionUtils.isEmpty(permissionList)) {
            return;
        }

        //获取所有菜单（my按钮）
        List<SysPermission> menuList = permissionList.stream().filter(p -> {
            return p.getType() == 1;
        }).collect(Collectors.toList());

        //收集每个菜单的子菜单到对应的chlid集合中
        buildChildren(menuList);
        List<SysPermission> result = Lists.newArrayList();
        menuList.stream().forEach(m->{
            if(m.getParentId()==(0L)){
                result.add(m);
            }
        });
        //重新设置到permissionList中
        sysUser.setPermissionList(result);
    }

    private void buildChildren(List<SysPermission> menuList) {

        menuList.stream().forEach(sysPermission -> {
            List<SysPermission> childMenu = Lists.newArrayList();
            List<String> childUrl = Lists.newArrayList();
            menuList.stream().forEach(p->{
                if(p.getParentId().equals(sysPermission.getId())){
                    childMenu.add(p);
                    childUrl.add(p.getUrl());
                }
                //设置子菜单
                sysPermission.setChildren(childMenu);
                sysPermission.setChildrenUrl(childUrl);
            });
        });

    }
}
